package com.atiguigu.rabbitmq.eight;

import com.atiguigu.rabbitmq.utils.RabbitMqUtils;
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DeliverCallback;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeoutException;

/*
* 死信队列实战
* */
public class Consumer01 {
    public static final String NORMAL_EXCHANGE= "normal_exchange";
    public static final String DEAD_EXCHANGE= "dead_exchange";//死信交换机
    public static final String NORMAL_QUEUE= "normal_queue";
    public static final String DEAD_QUEUE= "dead_queue";//死信队列

    public static void main(String[] args) throws IOException, TimeoutException {
       Channel channel = RabbitMqUtils.getChannel();
       //声明死信交换机和普通交换机
        channel.exchangeDeclare(NORMAL_EXCHANGE, BuiltinExchangeType.DIRECT);
        channel.exchangeDeclare(DEAD_EXCHANGE,BuiltinExchangeType.DIRECT);
        //普通队列，参数4：实现正常队列向死信队列消息的传送
        Map<String,Object> arguments=new HashMap<>();
        //过期时间,10s
        //arguments.put("x-message-ttl",100000);
        //正常队列设置死信交换机
        arguments.put("x-dead-letter-exchange",DEAD_EXCHANGE);
        //设置死信RountingKey
        arguments.put("x-dead-letter-rounting-key","lisi");
        //设置正常队列长度限制
        arguments.put("x-max-length",6);
        channel.queueDeclare(NORMAL_QUEUE,false,false,false,arguments);

        //死信队列
        channel.queueDeclare(DEAD_QUEUE,false,false,false,null);

        //绑定普通交换机-队列
        channel.queueBind(NORMAL_QUEUE,NORMAL_EXCHANGE,"zhangsan");
        //绑定死信交换机-队列
        channel.queueBind(DEAD_QUEUE,DEAD_EXCHANGE,"lisi");

        System.out.println("等待接收消息。。。");
        DeliverCallback deliverCallback=(consumerTag,message)->{
            System.out.println("Consumer01接收消息："+new String(message.getBody(),"UTF-8"));
        };

       channel.basicConsume(NORMAL_QUEUE,true,deliverCallback,consumerTag->{});
    }
}
